package handler

import (
	"context"
	"fmt"
	uuid2 "github.com/google/uuid"
	"order_srv/global"
	"order_srv/internal/model"
	"order_srv/internal/service"
	pb "order_srv/proto"
	"strconv"
	"time"
)

type OrderServer struct {
	pb.UnimplementedOrderServer
}

func (o *OrderServer) OrderCreate(ctx context.Context, req *pb.OrderCreateRequest) (resp *pb.OrderCreateResponse, err error) {

	key := "lock" + strconv.Itoa(int(req.UserId))
	err = global.Rdb.Get(ctx, key).Err()
	if err != nil {
		return nil, fmt.Errorf("获取锁失败")
	}

	product := service.FindProductInfo()
	if req.Num > int32(product.Num) {
		return nil, fmt.Errorf("库存不足,不能下单")
	} else {
		_, err := service.GetAllProductInfo()
		if err != nil {
			return nil, fmt.Errorf("提示用户库存不足")
		}
	}
	//创建订单
	uuid := uuid2.NewString()
	order := model.SysOrder{
		Sn:          uuid,
		UserID:      int(req.UserId),
		TotalNum:    int(req.Num),
		TotalPrice:  product.Price,
		CouPonPrice: 1,
		PayStatus:   0, //默认待支付
		Status:      1,
	}
	if err = global.DB.Create(&order).Error; err != nil {
		return nil, fmt.Errorf("订单创建失败")
	}
	orderProduct := model.SysOrderProduct{
		OrderID:   int(order.ID),
		ProductID: int(product.ID),
		Name:      product.Name,
		Price:     product.Price,
		Img:       product.Img,
		Types:     product.Types,
		Notes:     req.Notes,
	}
	if err = global.DB.Create(&orderProduct).Error; err != nil {
		return nil, fmt.Errorf("订单商品创建失败")
	}

	value := "success" + time.Now().Format(time.DateTime)
	err = global.Rdb.Set(ctx, key, value, time.Minute*2).Err()
	if err != nil {
		return nil, fmt.Errorf("获取锁失败")
	}
	return &pb.OrderCreateResponse{
		Sn:        order.Sn,
		CreatedAt: int32(order.CreatedAt.Unix()),
	}, nil
}

func (c *OrderServer) PayCreate(ctx context.Context, req *pb.PayCreateRequest) (resp *pb.PayCreateResponse, err error) {

	//查询某个用户订单的详情
	detailOrder := service.GetDetailOrder(int(req.OrderId), int(req.UserId))

	//查询商品详情
	detail := service.GetProductDetail(int(req.ProductId))

	//获取用户可以优惠券
	price := service.GetCouponPrice(int(req.CouponId), int(req.UserId))

	order := model.SysOrder{
		Sn:          detailOrder.Sn,
		UserID:      detailOrder.UserID,
		TotalNum:    detailOrder.TotalNum,
		TotalPrice:  detailOrder.TotalPrice * price.Price, //计算总价
		CouponID:    int(req.CouponId),                    //优惠券ID
		CouPonPrice: price.Price,                          //查询的优惠券金额
		PayID:       int(req.PayTypes),
	}
	err = global.DB.Create(&order).Error
	orderProduct := model.SysOrderProduct{
		OrderID:   int(order.ID),
		ProductID: int(detail.ID),
		Notes:     req.Notes,
	}
	//保存商品的评价
	global.DB.Save(&orderProduct)
	//修改库存
	product := model.SysProduct{
		Num: detail.Num - order.TotalNum,
	}
	global.DB.Where("id = ?", product.ID).Updates(&product)
	//创建积分
	score := model.Score{
		Scores: int(order.TotalPrice),
		UserID: int(req.UserId),
	}
	err = global.DB.Create(&score).Error
	if err != nil {
		return nil, fmt.Errorf("积分创建失败")
	}
	return &pb.PayCreateResponse{
		Price:   float32(order.TotalPrice),
		PayTime: int32(order.CreatedAt.Unix()),
	}, nil
}

func (o *OrderServer) OrderList(ctx context.Context, req *pb.OrderListRequest) (resp *pb.OrderListResponse, err error) {

	var order []model.SysOrder
	err = global.DB.Where("pay_status = ?", 1).Order("pay_status DESC").Find(&order).Error
	if err != nil {
		return nil, fmt.Errorf("展示失败")
	}
	var slice []*pb.OrderInfo
	for _, sysOrder := range order {
		slice = append(slice, &pb.OrderInfo{
			Sn:         sysOrder.Sn,
			TotalPrice: float32(sysOrder.TotalPrice),
			PayStatus:  int32(sysOrder.PayStatus),
			Status:     int32(sysOrder.Status),
		})
	}
	return &pb.OrderListResponse{OrderList: slice}, nil

}

func (o *OrderServer) CouponList(ctx context.Context, req *pb.CouponListRequest) (resp *pb.CouponListResponse, err error) {

	var coupon []model.SysCoupon
	err = global.DB.Where("types = ?", req.Types).Find(&coupon).Error
	if err != nil {
		return nil, fmt.Errorf("优惠券列表展示失败")
	}
	var slice []*pb.Coupon
	for _, sysCoupon := range coupon {
		slice = append(slice, &pb.Coupon{
			Types:    int32(sysCoupon.Types),
			Status:   int32(sysCoupon.Status),
			Price:    float32(sysCoupon.Price),
			Name:     sysCoupon.Name,
			MinPrice: float32(sysCoupon.MinPrice),
		})
	}
	return &pb.CouponListResponse{
		CouponList: slice,
	}, nil

}
func (o *OrderServer) Coupon(ctx context.Context, req *pb.CouponRequest) (resp *pb.CouponResponse, err error) {

	coupons := model.SysCoupon{
		UserId:   req.UserId,
		Types:    int(req.Types),
		Status:   int(req.Status),
		Price:    float64(req.Price),
		Name:     req.Name,
		MinPrice: float64(req.MinPrice),
	}
	if err = global.DB.Create(&coupons).Error; err != nil {
		return nil, fmt.Errorf("优惠券领取失败")
	}

	var coupon model.SysCoupon
	err = global.DB.Where("id = ? AND user_id = ?", coupons.ID, coupons.UserId).First(&coupon).Error
	if err != nil {
		return nil, err
	}
	if coupon.ID != 0 {
		return nil, fmt.Errorf("优惠券不能重复领取")
	}
	return &pb.CouponResponse{
		Msg: "优惠券领取成功",
	}, nil

}
func (o *OrderServer) UserCoupon(ctx context.Context, req *pb.UserCouponRequest) (resp *pb.UserCouponResponse, err error) {

	var coupon []model.SysCoupon
	//使用状态类型
	err = global.DB.Where("status = ?", req.Status).Find(&coupon).Error
	if err != nil {
		return nil, fmt.Errorf("优惠券查询失败")
	}
	var slice []*pb.Coupon
	for _, sysCoupon := range coupon {
		slice = append(slice, &pb.Coupon{
			Types:    int32(sysCoupon.Types),
			Status:   int32(sysCoupon.Status),
			Price:    float32(sysCoupon.Price),
			Name:     sysCoupon.Name,
			MinPrice: float32(sysCoupon.MinPrice),
		})
	}
	return &pb.UserCouponResponse{
		CouponList: slice,
	}, nil

}
